﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;

namespace PlanesManager.Utils
{
        public class Car
        {
            public int id { get; set; }
            public string manufacturer { get; set; }
            public string model { get; set; }
            public string car { get; set; }
            public string image { get; set; }
        }

        public class RentCarJsonAPI
        {
            public static ICollection<Car> getCars()
            {
                string url = "http://192.168.160.123:8080/Rent-a-Car/Cars/Available?token=84479224-fc0d-461c-a402-9c1ce176c8fb";
                string json = new WebClient().DownloadString(url);
                Car[] cars = JsonConvert.DeserializeObject<Car[]>(json);
                return cars.ToList();
            }

            public static string alugarCarro(int carID, string startDate, string endDate)
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://192.168.160.123:8080/Rent-a-Car/Cars/Rent?token=bb034a42-15a0-4107-b6b0-93de7fa2b5d8");
                httpWebRequest.ContentType = "text/json";
                httpWebRequest.Method = "POST";

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = "{\"carID\":\"" + carID + "\"," + "\"nif\":\"123456789\",\"beginDate\":\"" + startDate + ",\"endDate\":\"" + endDate + "\"}";

                    streamWriter.Write(json);
                    streamWriter.Flush();
                    streamWriter.Close();

                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        var result = streamReader.ReadToEnd();
                        JObject o = JObject.Parse(result);
                        return (string)o["invoice"];
                    }
                }
            }
        }
}